﻿using System;

using Ext.Net;
using ZP.Data;
using ZP.Service;
using Kwan.Helper.Strings;
using Kwan.Data;

namespace ZP.Web.Admin
{
    public partial class ExtLogin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.IsAuthenticated)
            {
                string returnURL = string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]) ? "~/Ext/Default.aspx" : Request.QueryString["ReturnUrl"];
                string x = Page.User.Identity.Name;
                Response.Redirect(returnURL, true);
            }
            if (!X.IsAjaxRequest)
            {
                btnVerify.ImageUrl = "~/Helper/VerifyCode.aspx?" + new Random().Next(100000);
            }
        }

        protected void btnVerify_Click(object sender, EventArgs e)
        {
            btnVerify.ImageUrl = "~/Helper/VerifyCode.aspx?" + new Random().Next(100000);
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            TUser u = (TUser.userName.Eq(txtUsername.Text)).ListFirst<TUser>();
            if (u == null)
            {
                ExtHelper.ErrorMsg("登录失败", "用户名错误！", this.btnLogin.ClientID);
                return;
            }
            if (u.Password != MD5.Md5Encrypt(txtPassword.Text))
            {
                ExtHelper.ErrorMsg("登录失败", "密码错误！", this.btnLogin.ClientID);
                return;
            }
            if (!Session["VerifyCode"].ToString().ToLower().Equals(txtCode.Text.ToLower()))
            {
                ExtHelper.ErrorMsg("登录失败", "验证码错误！", this.btnLogin.ClientID);
                return;
            }
            //写入cookie
            UserUtil.Login(u.UserName, u.RoleID.ToString(), txtRemember.Checked);
            //缓存信息
            UserUtil.GetModule(u.RoleID);
            //记录登录信息
            u.LoginCount = u.LoginCount + 1;
            DBContext.Save(u);

            //TLoginLog log = new TLoginLog();
            //log.IP = Request.UserHostAddress; log.LoginDate = DateTime.Now; log.Uid = u.id;
            //using (ClassMgr<TLoginLog> loginMgr = new ClassMgr<TLoginLog>())
            //    loginMgr.EntityDAO.Save(log);

            string returnURL = string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]) ? "~/Ext/Default.aspx" : Request.QueryString["ReturnUrl"];
            Response.Redirect(returnURL, true);
        }
    }
}